package com.zbec.mdrs.util;

import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/19.
 */
public class ReaderTxt {
    public Map<Object, Map> readTxtContent(MultipartFile file,Integer dataColumCount) {
        Map<Object, Map> content = new HashMap<Object, Map>();
        String s;
        Map<String,String> dataMap= new HashMap<String, String>();
        String dataDate="";
        try{
            String code=getCharset(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(),code));
            int i=1;
            s=br.readLine();
            while(s!=null && s.length()!=0){
                if(i>1){
                    Map<Integer, String> cellContent = new HashMap<Integer, String>();
                    String[] ss = s.split("\\t",-1);
                    for (int j=0;j<ss.length;j++){
                        if(j==dataColumCount && "".equals(dataDate)){
                            dataDate=ss[j];
                        }
                        cellContent.put(j,ss[j]);
                    }


                    content.put(i-1, cellContent);
                }
                i++;
                s=br.readLine();
            }
            dataMap.put("dataDate",dataDate);
            content.put("dataMap",dataMap);
            br.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return content;
    }

    private String getCharset(MultipartFile file) throws IOException{

        BufferedInputStream bin = new BufferedInputStream(file.getInputStream());
        int p = (bin.read() << 8) + bin.read();

        String code = null;

        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16BE";
                break;
            default:
                code = "GBK";
        }
        return code;
    }
}
